/**
 * 百度地图组件
 */
class BaiduMapComponent {
    constructor(containerId, options = {}) {
        this.containerId = containerId;
        this.options = {
            center: options.center || [116.404, 39.915],
            zoom: options.zoom || 12,
            enableGeolocation: options.enableGeolocation || true,
            onLocationSelected: options.onLocationSelected || null,
            onMapInitialized: options.onMapInitialized || null
        };
        this.map = null;
        this.markers = new Map();
        this.infoWindows = new Map();
        this.routes = new Map();
        this.driving = null;
        this.currentMarker = null;
        this.searchTimeout = null;
    }

    waitForBaiduMap() {
        return new Promise((resolve, reject) => {
            if (window.BMapGL) {
                resolve();
            } else {
                const checkBMap = () => {
                    if (window.BMapGL) {
                        resolve();
                    } else {
                        setTimeout(checkBMap, 100);
                    }
                };
                checkBMap();
                // 设置超时
                setTimeout(() => {
                    reject(new Error('百度地图API加载超时'));
                }, 10000);
            }
        });
    }

    async init() {
        try {
            // 等待百度地图API加载完成
            await this.waitForBaiduMap();
            
            // 初始化地图
            this.map = new BMapGL.Map(this.containerId);
            const center = new BMapGL.Point(...this.options.center);
            this.map.centerAndZoom(center, this.options.zoom);
            
            // 添加地图控件
            this.map.enableScrollWheelZoom();
            this.map.addControl(new BMapGL.ScaleControl());
            this.map.addControl(new BMapGL.ZoomControl());
            this.map.addControl(new BMapGL.NavigationControl());
            
            // 点击地图事件
            this.map.addEventListener('click', (e) => {
                const point = e.point;
                this.setMarkerAndAddress(point);
            });

            // 初始化驾车路线规划
            this.driving = new BMapGL.DrivingRoute(this.map, {
                renderOptions: {
                    map: this.map,
                    autoViewport: true
                }
            });

            // 如果启用了地理定位
            if (this.options.enableGeolocation) {
                await this.getCurrentLocation();
            }

            // 调用初始化完成回调
            if (typeof this.options.onMapInitialized === 'function') {
                this.options.onMapInitialized(this.map);
            }
        } catch (error) {
            console.error('地图初始化失败:', error);
            throw error;
        }
    }

    async getCurrentLocation() {
        return new Promise((resolve, reject) => {
            const geolocation = new BMapGL.Geolocation();
            geolocation.getCurrentPosition(
                position => {
                    if (geolocation.getStatus() === BMAP_STATUS_SUCCESS) {
                        const point = position.point;
                        this.map.centerAndZoom(point, 16);
                        this.setMarkerAndAddress(point);
                        resolve(point);
                    } else {
                        console.error('定位失败:', geolocation.getStatus());
                        reject(new Error('定位失败: ' + geolocation.getStatus()));
                    }
                },
                { enableHighAccuracy: true }
            );
        });
    }

    setMarkerAndAddress(point) {
        // 清除现有标记
        if (this.currentMarker) {
            this.map.removeOverlay(this.currentMarker);
        }

        // 添加新标记
        this.currentMarker = new BMapGL.Marker(point);
        this.map.addOverlay(this.currentMarker);
        
        // 获取地址信息
        const geocoder = new BMapGL.Geocoder();
        geocoder.getLocation(point, (result) => {
            if (result) {
                if (typeof this.options.onLocationSelected === 'function') {
                    this.options.onLocationSelected({
                        address: result.address,
                        latitude: point.lat,
                        longitude: point.lng
                    });
                }
            }
        });
    }

    searchAddress(keyword) {
        if (!keyword) return;

        // 防抖处理
        if (this.searchTimeout) {
            clearTimeout(this.searchTimeout);
        }

        this.searchTimeout = setTimeout(() => {
            const local = new BMapGL.LocalSearch(this.map, {
                onSearchComplete: (results) => {
                    if (local.getStatus() === BMAP_STATUS_SUCCESS && results.getCurrentNumPois()) {
                        const firstResult = results.getPoi(0);
                        const point = firstResult.point;
                        this.map.centerAndZoom(point, 16);
                        this.setMarkerAndAddress(point);
                    }
                }
            });
            local.search(keyword);
        }, 500);
    }

    addMarker(id, point, options = {}) {
        // 清除已存在的相同ID的标记
        if (this.markers.has(id)) {
            this.clearMarker(id);
        }

        const marker = new BMapGL.Marker(point);
        this.map.addOverlay(marker);
        this.markers.set(id, marker);

        // 如果有信息窗口配置
        if (options.infoWindow) {
            const infoWindow = new BMapGL.InfoWindow(options.infoWindow.content, {
                title: options.infoWindow.title,
                width: 300,
                height: 200
            });
            this.infoWindows.set(id, infoWindow);
            
            marker.addEventListener('click', () => {
                this.map.openInfoWindow(infoWindow, point);
            });
        }

        return marker;
    }

    clearMarker(id) {
        if (this.markers.has(id)) {
            this.map.removeOverlay(this.markers.get(id));
            this.markers.delete(id);
        }
        if (this.infoWindows.has(id)) {
            this.infoWindows.delete(id);
        }
    }

    clearAllMarkers() {
        this.markers.forEach(marker => {
            this.map.removeOverlay(marker);
        });
        this.markers.clear();
        this.infoWindows.clear();
    }

    setView(center, zoom) {
        const point = new BMapGL.Point(center[0], center[1]);
        this.map.centerAndZoom(point, zoom);
    }

    addRoute(start, end) {
        const startPoint = new BMapGL.Point(start[0], start[1]);
        const endPoint = new BMapGL.Point(end[0], end[1]);
        this.driving.search(startPoint, endPoint);
    }

    clearRoute() {
        this.driving.clearResults();
    }
} 